package com.healthcloud.service.impl;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.healthcloud.dao.PhysicalExamMapper;
import com.healthcloud.dao.TestProjectItemMapper;
import com.healthcloud.dao.TestProjectKindMapper;
import com.healthcloud.dao.TestReferenceValueMapper;
import com.healthcloud.dao.TestResultMapper;
import com.healthcloud.entity.Condition;
import com.healthcloud.entity.ExamData;
import com.healthcloud.entity.PhysicalExam;
import com.healthcloud.entity.PhysicalExamCriteria;
import com.healthcloud.entity.TestProjectItem;
import com.healthcloud.entity.TestProjectKind;
import com.healthcloud.entity.TestReferenceValue;
import com.healthcloud.entity.TestResult;
import com.healthcloud.entity.TestResultApp;
import com.healthcloud.entity.TestResultCriteria;
import com.healthcloud.query.CriteriaUtils;
import com.healthcloud.search.Criteria;
import com.healthcloud.service.HealthExamService;
import com.healthcloud.utils.Base64ImgUtil;
import com.healthcloud.utils.DateUtils;
import com.healthcloud.utils.PageParam;
import com.healthcloud.utils.Pagine;
import com.healthcloud.vo.PatientVo;

/**
 * Created by xiam on 2015/6/22.
 */
@Service("healthExamService")
public class HealthExamServiceImpl implements HealthExamService {

	@Autowired
	private TestResultMapper testResultMapper;
	@Autowired
	private PhysicalExamMapper physicalExamMapper;
	@Autowired
	private TestProjectItemMapper testProjectItemMapper;
	@Autowired
	private TestProjectKindMapper testProjectKindMapper;
	//add by lixiaoxiao 20170118 
	@Autowired
	private TestReferenceValueMapper testreferenceValueMapper;
	

	@Override
	public List<PhysicalExam> save(List<PhysicalExam> examDataList) {
		if (examDataList != null && examDataList.size() > 0) {
			for (PhysicalExam phExam : examDataList) {
				phExam.setCreatedTime(new Date());
				physicalExamMapper.save(phExam);
			}
		}
		return null;
	}

	@Override
	public List<ExamData> findByExamId(Long examId) {
		return null;
	}

	@Override
	public PhysicalExam findByExamIdAndIdNum(String examId, String idCard) {
		PhysicalExam entity = new PhysicalExam();
		if(StringUtils.isNotBlank(examId)){
			entity.setMkExamCode(examId);
		}
		if(StringUtils.isNotBlank(idCard)){
			entity.setIdCard(idCard);
		}
		entity.setIsFast(null);
		entity.setIsNormal(null);
		List<PhysicalExam> list = physicalExamMapper.findByEntity(entity,null);
		if(list!=null&&list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}

	@Transactional
	@Override
	public PhysicalExam parseJson4Physical(Map<String, String> jsonMap) {
		// Map<String,String> jsonMap = JsonHelper.toMap(jsonStr);
		PhysicalExam exam = new PhysicalExam();
		if (jsonMap != null && !jsonMap.isEmpty()) {
			String actId = jsonMap.get("id");
			if (!StringUtil.isBlank(actId)) {
				Long id = Long.valueOf(actId);
				if (id > 0) {
					exam = physicalExamMapper.get(id);
				}
			}
			if (!StringUtil.isBlank(jsonMap.get("idCard"))) {
				//身份证号转小写存储
				exam.setIdCard(jsonMap.get("idCard").toLowerCase());
			}
			if (!StringUtil.isBlank(jsonMap.get("examDate"))) {
				Date dt = DateUtils.strToDate(jsonMap.get("examDate") + "",
						"yyyy-MM-dd HH:mm:ss");
				exam.setExamDate(dt);
			}
			if (!StringUtil.isBlank(jsonMap.get("mkExamCode"))) {
				exam.setMkExamCode(jsonMap.get("mkExamCode"));
			}
			if (!StringUtil.isBlank(jsonMap.get("mkExamCode"))) {
				exam.setHisExamCode(jsonMap.get("mkExamCode"));
			}
			if (!StringUtil.isBlank(jsonMap.get("isFast"))) {
				exam.setIsFast(Integer.valueOf(jsonMap.get("isFast")));
			}
			if (!StringUtil.isBlank(jsonMap.get("isNormal"))) {
				exam.setIsNormal(Integer.valueOf(jsonMap.get("isNormal")));
			}
			exam.setDoctorName(jsonMap.get("doctorName"));
			if (!StringUtil.isBlank(jsonMap.get("doctorId"))) {
				exam.setDoctorId(Integer.valueOf(jsonMap.get("doctorId")));
			}
			if (!StringUtil.isBlank(jsonMap.get("bodyIdentificationResult"))) {
				exam.setBodyIdentificationResult(jsonMap
						.get("bodyIdentificationResult"));
			}
			if (!StringUtil.isBlank(jsonMap.get("dietaryGuidanceResult"))) {
				exam.setDietaryGuidanceResult(jsonMap
						.get("dietaryGuidanceResult"));
			}
			if (!StringUtil.isBlank(jsonMap.get("sportGuidanceResult"))) {
				exam.setSportGuidanceResult(jsonMap.get("sportGuidanceResult"));
			}
			if (!StringUtil.isBlank(jsonMap.get("doctorSummary"))) {
				exam.setDoctorSummary(jsonMap.get("doctorSummary"));
			}
			if (StringUtil.isBlank(actId) || actId == "0") {
				exam.setCreatedTime(new Date());
				physicalExamMapper.save(exam);
			} else {
				exam.setUpdatedTime(new Date());
				physicalExamMapper.update(exam);
			}
		}
		return exam;
	}

	@Transactional
	@Override
	public TestResult parseJson4Instrument(Map<String, String> jsonMap) {
		// Map<String,String> jsonMap = JsonHelper.toMap(jsonStr);
		TestResult testResult = new TestResult();
		if (jsonMap != null && !jsonMap.isEmpty()) {
			String actId = jsonMap.get("TestId");
			if (!StringUtil.isBlank(actId)) {
				Long id = Long.valueOf(actId);
				if (id > 0) {
					testResult = testResultMapper.get(id);
				}
			}
			if (!StringUtil.isBlank(jsonMap.get("idCard"))) {
				//身份证号转小写存储
				testResult.setIdCard(jsonMap.get("idCard").toLowerCase());
			}
			String testItemCode = jsonMap.get("testItemCode");
			TestProjectItem item = null;
			if (!StringUtil.isBlank(testItemCode)) {
				testResult.setTestItemCode(testItemCode);
				item = selectItem(testItemCode);
			}
			if (!StringUtil.isBlank(jsonMap.get("testItemName"))) {
				testResult.setTestItemName(jsonMap.get("testItemName"));
			} else {
				if (item != null) {
					testResult.setTestItemName(item.getTestItemName());
				}
			}
			if (!StringUtil.isBlank(jsonMap.get("testItemNameEn"))) {
				testResult.setTestItemNameEn(jsonMap.get("testItemNameEn"));
			} else {
				if (item != null) {
					testResult.setTestItemNameEn(item.getTestItemNameEn());
				}
			}
			
			String testKindCode = jsonMap.get("testKindCode");
			TestProjectKind kind = null;
			if (!StringUtil.isBlank(testKindCode)) {
				testResult.setTestKindCode(testKindCode);
				kind = selectKind(testKindCode);
			}
			if (!StringUtil.isBlank(jsonMap.get("testKindName"))) {
				testResult.setTestKindName(jsonMap.get("testKindName"));
			} else {
				if (kind != null) {
					testResult.setTestKindName(kind.getTestKindName());
				}
			}
			if (!StringUtil.isBlank(jsonMap.get("testKindNameEn"))) {
				testResult.setTestKindNameEn(jsonMap.get("testKindNameEn"));
			} else {
				if (kind != null) {

				}
			}
			if (!StringUtil.isBlank(jsonMap.get("testTime"))
					&& !StringUtil.isBlank(jsonMap.get("testDate"))) {
				String dateTime = jsonMap.get("testDate") + " "
						+ jsonMap.get("testTime");
				Date dt = DateUtils.strToDate(dateTime, "yyyy-MM-dd HH:mm:ss");
				testResult.setTestTime(dt);
			} else {
				Date dateTime = new Date();
				testResult.setTestTime(dateTime);
			}
			if (!StringUtil.isBlank(jsonMap.get("valueUnit"))) {
				testResult.setValueUnit(jsonMap.get("valueUnit"));
			}else{
				//设置单位值  add by lixiaoxiao 20170118
				if (item != null) {
					testResult.setValueUnit(item.getTestUnit());
				}
			}
			//-- begin add by lixiaoxiao 20170118 添加参考值高低
			List<TestReferenceValue> list = testreferenceValueMapper.getByItemCode(testItemCode);
			if(list.size() > 0){
				testResult.setConsultHigh(String.valueOf(list.get(0).getTestMaxValue()));
				testResult.setConsultLow(String.valueOf(list.get(0).getTestMinValue()));
			}
			//-- end add by lixiaoxiao 20170118 添加参考值高低
			if (!StringUtil.isBlank(jsonMap.get("testValue"))) {
				testResult.setTestValue(jsonMap.get("testValue"));
			}else{
				testResult.setTestValue("");
			}
			if (!StringUtil.isBlank(jsonMap.get("testReport"))) {
				testResult.setTestReport(jsonMap.get("testReport"));
			}
			if (!StringUtil.isBlank(jsonMap.get("testResult"))) {
				testResult.setTestResult(jsonMap.get("testResult"));
			}
			if (!StringUtil.isBlank(jsonMap.get("resultKind"))) {
				testResult.setResultKind(Integer.valueOf(jsonMap
						.get("resultKind")));
			}
			if (!StringUtil.isBlank(jsonMap.get("medicalInstrumentName"))) {
				testResult.setMedicalInstrumentName(jsonMap
						.get("medicalInstrumentName"));
			}
			if (!StringUtil.isBlank(jsonMap.get("mkMedicalInstrumentId"))) {
				testResult.setMkMedicalInstrumentId(jsonMap
						.get("mkMedicalInstrumentId"));
			}
			if (!StringUtil.isBlank(jsonMap.get("testPersonName"))) {
				testResult.setTestPersonName(jsonMap.get("testPersonName"));
			}
			if (!StringUtil.isBlank(jsonMap.get("testPersonId"))) {
				testResult.setTestPersonId(jsonMap.get("testPersonId"));
			}
			if (!StringUtil.isBlank(jsonMap.get("testPersonKindId"))) {
				testResult.setTestPersonKindId(Integer.valueOf(jsonMap
						.get("testPersonKindId")));
			}
			if (!StringUtil.isBlank(jsonMap.get("testFrom"))) {
				testResult
						.setTestFrom(Integer.valueOf(jsonMap.get("testFrom")));
			}
			if (!StringUtil.isBlank(jsonMap.get("fromId"))) {
				testResult.setFromId(jsonMap.get("fromId"));
			}
			if (!StringUtil.isBlank(jsonMap.get("temprature"))) {
				testResult.setTemprature(jsonMap.get("temprature"));
			}
			if (StringUtil.isBlank(actId) || actId == "0" || actId.equals("0")) {
				testResultMapper.save(testResult);
			} else {
				testResultMapper.update(testResult);
			}
		}
		return testResult;
	}

	//按照时间和项目获得分组数据
	public List<TestResult> getGroups(Map<String, String> jsonMap,String groupBy){
		List<TestResult> groups = testResultMapper
				.groupBy(getConditions(conditionByJsonMap(jsonMap)),groupBy);
		return groups;
	}
	// 根据分组数据查询体检详细数据
	public List<Map<String,String>> findVo(Map<String, String> jsonMap) {
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
		String groupBy = "  testTime,testKindCode,idCard";
		List<TestResult> groups = getGroups(jsonMap, groupBy);//按时间和项目分组
		if (groups != null && groups.size() > 0) {
			for (TestResult trs : groups) {
				String code = trs.getTestKindCode();
				Date time = trs.getTestTime();
				String idCard = jsonMap.get("idCard");
				TestResult trCon = new TestResult();
				trCon.setTestKindCode(code);
				trCon.setIdCard(idCard);
				trCon.setTestTime(time);
				List<TestResult> res = testResultMapper
						.findByEntity(trCon,null);
				Map map = packVo(res);
				if(map!=null){
					mapList.add(map);
				}
			}
		}
		return mapList;
	}
	
    // 按时间分组
	public List<Map<String,String>> findVo2(Map<String, String> jsonMap) {
		List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
		String groupBy = "  lastExamDate ";
		List<PatientVo> groups = testResultMapper
				.groupBy2(getConditions(conditionByJsonMap(jsonMap)), groupBy);
		if (groups != null && groups.size() > 0) {
			for (PatientVo pv : groups) {
				Map<String,String> map = new HashMap();
				String dt = pv.getLastExamDate();
				map.put("testDate", dt);
				mapList.add(map);
			}
		}
			return mapList;
		}

	// 按照种类和时间组装结果集
	private Map<String,String> packVo(List<TestResult> results) {
		Map<String,String> dataMap = null;
		if (results != null && results.size() > 0) {
			dataMap = new HashMap<String,String>();
			for (TestResult result : results) {
				if(!dataMap.containsKey("testKindCode")){
					dataMap.put("testKindCode", result.getTestKindCode());
				}
				if(!dataMap.containsKey("testKindName")){
					dataMap.put("testKindName", result.getTestKindName());
				}
				if(!dataMap.containsKey("testTime")){
					Date date = result.getTestTime();
					if(date!=null){
						String dt = DateUtils.format(DateUtils.Date2Calendar(date), "yyyy-MM-dd HH:mm:ss");
						dataMap.put("testTime", dt);
					}
				}
				String code = result.getTestItemCode();
				if(!dataMap.containsKey(code)){
					dataMap.put(result.getTestItemCode(), result.getTestValue());
				}
			}
		}
		return dataMap;
	}

	// 根据查询map中的字段组装查询条件
	public TestResultCriteria conditionByJsonMap(Map<String, String> dataMap) {
		String testId = dataMap.get("testId");
		String idCard = dataMap.get("idCard");
		String MKMedicalinstrumenId = dataMap.get("mkMedicalInstrumentId");
		String testKindCode = dataMap.get("testKindCode");
		String testItemCode = dataMap.get("testItemCode");
		String testTimeFrom = dataMap.get("testTimeFrom");
		String testTimeTo = dataMap.get("testTimeTo");
		TestResultCriteria tc = new TestResultCriteria();
		if(StringUtils.isNotBlank(idCard)){
			tc.setIdCard(idCard);
		}
		if(StringUtils.isNotBlank(MKMedicalinstrumenId)){
			tc.setMkMedicalInstrumentId(MKMedicalinstrumenId);
		}
		if(StringUtils.isNotBlank(testItemCode)){
			tc.setTestItemCode(testItemCode);
		}
		if(StringUtils.isNotBlank(testKindCode)){
			tc.setTestKindCode(testKindCode);
		}
		if (!StringUtil.isBlank(testId)) {
			tc.setTestId(new BigDecimal(testId));
		}
		if (!StringUtil.isBlank(testTimeFrom)) {
			Date dtFrom = DateUtils.String2Datetime(testTimeFrom+" "+"00:00:00", "yyyy-MM-dd HH:mm:ss").toDate();
			tc.setTestTimeFrom(dtFrom);
		}
		if (!StringUtil.isBlank(testTimeTo)) {
			Date dtTo = DateUtils.String2Datetime(testTimeTo+" "+"23:59:59", "yyyy-MM-dd HH:mm:ss").toDate();
			tc.setTestTimeTo(dtTo);
		}
		return tc;
	}
	
	public List<PhysicalExam> selectList4PhysicalExam(String whereCondition){
		return physicalExamMapper.customCondition(whereCondition);
	}

	@Override
	public List<TestResult> findByEntity(TestResult entity) {
		List<TestResult> results = new ArrayList<TestResult>();
		results = testResultMapper.findByEntity(entity,null);
		return results;
	}

	@Override
	public List<TestResult> search4Result(TestResultCriteria criteria) {
		List<TestResult> trs = new ArrayList<TestResult>();
		List<Condition<Object>> conditions = getConditions(criteria);
		trs = testResultMapper.criteriaSearch(conditions, null);
		return trs;
	}

	@Override
	public List<PhysicalExam> search4Physical(PhysicalExamCriteria criteria) {
		List<PhysicalExam> phyExams = new ArrayList<PhysicalExam>();
		List<Condition<Object>> conditions = getConditions(criteria);
		phyExams = physicalExamMapper.criteriaSearch(conditions, null);
		return phyExams;
	}

	@Override
	public Page<TestResult> search(TestResultCriteria criteria,
			Pageable pageable) {
		List<Condition<Object>> conditions = getConditions(criteria);
		Pagine<TestResult> pagine = new Pagine<>(pageable);
		testResultMapper.criteriaSearch(conditions, pagine);
		return pagine;
	}

	@Override
	public Page<PhysicalExam> search(PhysicalExamCriteria criteria,Pageable pageable) {
		List<Condition<Object>> conditions = getConditions(criteria);
		Pagine<PhysicalExam> pagine = new Pagine<>(pageable);
		physicalExamMapper.criteriaSearch(conditions, pagine);
		return pagine;
	}
	
	@Override
	public Page<PhysicalExam> search(PhysicalExamCriteria criteria,int size,int page,Sort sort) {
		List<Condition<Object>> conditions = getConditions(criteria);
		Pagine<PhysicalExam> pagine = new Pagine<>(page,size,sort);
		physicalExamMapper.criteriaSearch(conditions, pagine);
		return pagine;
	}
	
	//组装查询条件
	private List<Condition<Object>> getConditions(Criteria criteria) {
		return CriteriaUtils.getConditions(criteria);
	}

	//返回体检小类项目
	@Override
	public TestProjectItem selectItem(String code) {
		return testProjectItemMapper.get(code);
	}

	//返回体检种类（大类）
	@Override
	public TestProjectKind selectKind(String code) {
		return testProjectKindMapper.get(code);
	}

	//返回体检种类列表（大类）
	@Override
	public List<TestProjectKind> findAllKinds() {
		TestProjectKind entity = new TestProjectKind();
		return testProjectKindMapper.findByEntityAll(entity);
	}
	
	//头像生成
	@Override
	public String faceImage(String idCard,String imageCode,HttpServletRequest request){
		 boolean flg = false;
		 String separator = File.separator;// 分隔符（防止linux分隔符不同报错）
		 String realPath = request.getSession().getServletContext().getRealPath(separator); // 项目绝对路径
		 String contextPath = request.getContextPath(); // 项目相对路径
		 String fileDir = "assets" + separator + "report" +separator;//服务器资源文件夹
		 String personalFolder = realPath+fileDir+idCard+separator;
		 String imageName = idCard+"_face.jpg";
		 File file = new File(personalFolder);
		 if(!file.exists()&& !file.isDirectory()){
			 file.mkdir();
		 }else{
			 File image = new File(personalFolder+imageName);
			 if(!image.exists()){
				 flg = Base64ImgUtil.GenerateImage(imageCode, personalFolder + imageName);
			 }else{
				 flg = true;
			 }
		 }
		 if(flg){
			 return contextPath+separator+fileDir+idCard+separator+imageName;
		 }else{
			 return contextPath+separator+"assets" +separator+
					"theme"+separator+"theme1.0"+separator+"img"+separator+"pic.png";
		 }
	}

	/**
	 * 获取smart检测数据
	 * 109<=id<=130
	 * @param idCard		身份证号码
	 * @param testTimeFrom	开始时间
	 * @param testTimeTo	结束时间
	 * @return List<TestResult>
	 */
	@Override
	public List<TestResult> getSmart(String idCard, String testTimeFrom, String testTimeTo){
		return testResultMapper.getSmart(idCard, testTimeFrom, testTimeTo);
	}

	/**
	 * 获取smart检测数据testKindCode，testKindName，testTime分组信息
	 * 109<=id<=130
	 * @param idCard		身份证号码
	 * @param testTimeFrom	开始时间
	 * @param testTimeTo	结束时间
	 * @return List<TestResult>
	 */
	@Override
	public List<TestResult> getSmartGroup(String idCard, String testTimeFrom, String testTimeTo) {
		return testResultMapper.getSmartGroup(idCard, testTimeFrom, testTimeTo);
	}

	@Override
	public List<TestResultApp> searchTestResultByDay(TestResultApp entity,PageParam pageParam) {

		return testResultMapper.searchListByDay(entity,pageParam);
	}

	@Override
	public void save(TestResult result) {
		testResultMapper.save(result);
	}
}
